import {deepClone, getFileAccessHttpUrl, isArray, isEmpty} from "@/util/common"
import {responseError, responseSuccess} from "@/util/response";
/**
 * 定义上传业务路径，用于构建文件上传接口的请求路径。
 * 此路径是服务器上用于接收和处理文件上传请求的特定路径，通常与静态资源路径和接口路径分开管理。
 */
export const baseUploadBizPath = 'share/car'

/**
 * 获取上传业务路径
 * @param path
 * @returns {string}
 */
export const getUploadBizPath = (path = '') => {
  return baseUploadBizPath + '/' + path
}

/**
 * 将字符串转换为文件列表
 * @param str
 * @returns {*[]}
 */
export const processFileListFromString = (str = '') => {
  if (isEmpty(str)) {
    return []
  }
  let list = str?.split(',') || []
  if (isEmpty(list)) {
    return []
  }
  let fileList = []
  for (const item of list) {
    fileList.push(uploadSuccess({}, item))
  }
  return fileList
}

/**
 * 获取上传成功的文件路径
 * @param list
 * @returns {string}
 */
export const getSuccessFilePaths = (list = []) => {
  let arr = []
  console.log('getModelStrByFileList list', list)
  for (const item of list) {
    if (item?.status !== 'success') {
      continue
    }
    arr.push(item.submitFilePath)
  }
  if (isEmpty(arr)) {
    return ''
  }
  return arr.join(',')
}

export const uploadError = (file, message = '上传失败') => {
  file.status = 'failed';
  file.message = message;
  file.url = ''
  return deepClone(file)
};

export const uploadSuccess = (file, url) => {
  file.status = 'done';
  file.message = '上传完成';
  file.url = getFileAccessHttpUrl(url)
  file.submitFilePath = url
  return deepClone(file)
};

export const uploadLoading = (file) => {
  file.status = 'uploading';
  file.message = '上传中...';
  return deepClone(file)
};


/**
 * 判断图片类型
 * @param filename
 * @returns {boolean}
 */
export const isImageType = (filename) => {
  // 正则表达式匹配常见的图片扩展名
  const imageRegex = /\.(jpg|jpeg|png|gif|bmp|webp|tiff|svg)$/i;
  return imageRegex.test(filename);
}
/**
 * 判断音频类型
 * @param filename
 * @returns {boolean}
 */
export const isAudioType = (filename) => {
  // 正则表达式匹配常见的音频扩展名
  const audioRegex = /\.(mp3|wav|aac|ogg|flac|m4a|wma|aiff|alac|opus)$/i;
  return audioRegex.test(filename);
}

const fileTypeCheckers = {
  image: {
    check: isImageType,
    message: '请上传图片'
  },
  audio: {
    check: isAudioType,
    message: '请上传录音文件'
  },
};

const checkFileType = (filename, fileType = 'image' ) => {
  const checker = fileTypeCheckers[fileType];
  if (isEmpty(checker)) {
    return responseSuccess()
  }
  if (checker.check(filename)) {
    return responseSuccess()
  }
  return responseError(checker.message)
};


export const useUploadProcessing = ({
                                      bizPath = '',
                                      formData = {},
                                      fileList = ref([]),
                                      fileType = 'image',
                                      api = {},
                                    }) => {
  // 删除文件
  const delUploadFile = (event) => {
    fileList.value.splice(event.index, 1)
  }
  
  // 新增文件
  const afterReadUpload = (event) => {
    console.log('afterReadUpload event ', event)
    // // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
    let lists = event
    if (!isArray(event)) {
      lists = [].concat(event)
    }
    lists.map((item) => {
      itemUploadFile(item)
    })
  }
  
  
  const itemUploadFile = async (file) => {
    console.log('itemUploadFile file', file)
    console.log('itemUploadFile fileType', fileType)
    uploadLoading(file)
    const checkResult = checkFileType(file.file.name, fileType)
    if (!checkResult.success) {
      console.log('checkFileType error', checkResult)
      uploadError(file, checkResult.msg)
      return
    }
    const result = await uploadFileRequest(file.file)
    if (result === false || !result.success) {
      uploadError(file)
      return
    }
    uploadSuccess(file, result.data)
  }
  
  // const getBase
  const uploadFileRequest = async (url) => {
    let res = {}
    try {
      res = await api({
        params: {
          bizPath: getUploadBizPath(bizPath),
          ...formData,
        },
        filePath: url,
        name: 'file',
      })
    } catch (e) {
      console.log('uploadFileRequest error', e)
      return responseError('上传失败')
    }
    if (!res.success) {
      return responseError(res.message)
    }
    return responseSuccess(res.result)
  }
  return {
    fileList,
    delUploadFile,
    afterReadUpload,
  }
  
}
